<template>
    <div class="list-box">
        <div class="pannel-title pannel-between">
            <div>管理员列表</div>
            <a-button class="pannel-btn" size="small" type="primary" shape="round" @click="addAdmin()">
                <PlusCircleFilled />
                新增管理员
            </a-button>
        </div>
        <div class="line"></div>
        <div class="data-table">
            <a-table :columns="columns" :row-key="(record) => record.id" :data-source="dataSource" :pagination="pagination" :loading="isLoading" @change="handleTableChange">
                <template #status="{text}">
                    <span class="span-green" v-if="text === 'Y'">已启用</span>
                    <span class="span-red" v-if="text === 'N'">已禁用</span>
                </template>
                <template #action="{record}">
                    <a style="margin-right: 5px" title="查看详情" @click="detail(record)"><img src="@/assets/images/yulan.png"/></a>
                    <a @click="editAdmin(record)" title="编辑" style="margin-right:5px;"><img src="@/assets/images/cz-edit.png"/></a>
                    <a @click="deleteAdmin(record)" title="删除"><img src="@/assets/images/cz-delete.png"/></a>
                </template>
            </a-table>
            <a-modal v-model:visible="visible" :maskClosable="false" :afterClose="closeModal">
                <h3 class="modal-title">{{ formState.id ? "修改" : "新增" }}</h3>
                <div class="modal-form">
                    <a-form ref="form1" :model="formState" :rules="rules" :labelCol="{ span: 6, offset: 0 }">
                        <a-form-item label="联系人" name="contactName">
                            <a-input v-model:value="formState.contactName" placeholder="请输入联系人" />
                        </a-form-item>
                        <a-form-item label="联系人手机" name="contactMobile">
                            <a-input v-model:value="formState.contactMobile" placeholder="请输入联系手机" />
                        </a-form-item>
                        <a-form-item label="登录账号" name="loginId">
                            <a-input v-model:value="formState.loginId" placeholder="请输入登录账号" />
                        </a-form-item>
                        <a-form-item label="登录密码" name="loginPw" :rules="rules.loginPw">
                            <a-input v-model:value="formState.loginPw" placeholder="请输入登录密码">
                                <template #suffix>
                                    <a-tooltip title="密码由6位以上数字、字母或者‘-’、‘_’、‘\’组成">
                                        <info-circle-outlined style="color: rgba(255, 0, 0, 0.7)" />
                                    </a-tooltip>
                                </template>
                            </a-input>
                        </a-form-item>
                        <a-form-item label="账号角色" name="name">
                            <a-select v-model:value="formState.roleId" style="width: 240px" :options="roleList" placeholder="请选择角色"></a-select>
                        </a-form-item>
                        <a-form-item label="状态" name="status">
                            <a-radio-group name="status" v-model:value="formState.status">
                                <a-radio value="Y">启用</a-radio>
                                <a-radio value="N">禁用</a-radio>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item label="二次验证" name="otpStatus">
                            <a-radio-group name="otpStatus" v-model:value="formState.otpStatus">
                                <a-radio value="Y">启用</a-radio>
                                <a-radio value="N">禁用</a-radio>
                            </a-radio-group>
                        </a-form-item>
                    </a-form>
                </div>
                <template #footer>
                    <div class="modal-btn">
                        <a-button type="default" shape="round" @click="closeModal">取消</a-button>
                        <a-button type="primary" shape="round" @click="confirm()">确定</a-button>
                    </div>
                </template>
            </a-modal>
            <a-modal v-model:visible="visible2" :maskClosable="false" :afterClose="closeModal2">
                <h3 class="modal-title">管理员详情</h3>
                <div class="modal-form">
                    <a-form ref="form1" :labelCol="{ span: 6, offset: 0 }">
                        <a-form-item label="联系人">
                            {{ activeItem.contact_name }}
                        </a-form-item>
                        <a-form-item label="联系人手机">
                            {{ activeItem.contact_mobile }}
                        </a-form-item>
                        <a-form-item label="登录账号">
                            {{ activeItem.login_id }}
                        </a-form-item>
                        <a-form-item label="账号角色">
                            {{ activeItem.role_name }}
                        </a-form-item>
                        <a-form-item label="状态">
                            {{ activeItem.status === "Y" ? "启用" : "禁用" }}
                        </a-form-item>
                        <a-form-item label="二次验证">
                            {{ activeItem.otp_status === "Y" ? "启用" : "禁用" }}
                        </a-form-item>
                        <a-form-item label="二次验证二维码">
                            <img :src="activeItem.qrcodeDataUrl" style="width:120px;height:120px;display:block;" />
                            <a-button type="primary" @click="updateSecret()">更新二次验证密钥</a-button>
                        </a-form-item>
                    </a-form>
                </div>
            </a-modal>
        </div>
    </div>
</template>
<script>
import { PlusCircleFilled, InfoCircleOutlined } from "@ant-design/icons-vue";
import { useStore } from "vuex";
import { reactive, ref } from "@vue/reactivity";
import { message, Table, Modal, Button, Form, Input, Select, Tooltip, Radio } from "ant-design-vue";
import httpRequest from "@/util/httpRequest";
import baseUtil from "@/util/baseUtil";
import validator from "@/util/validator";
import QRCode from "qrcode";
export default {
    components: {
        PlusCircleFilled,
        InfoCircleOutlined,
        ATable: Table,
        AModal: Modal,
        AButton: Button,
        AForm: Form,
        AFormItem: Form.Item,
        ASelect: Select,
        ARadio: Radio,
        ARadioGroup: Radio.Group,
        AInput: Input,
        ATooltip: Tooltip,
    },
    setup() {
        const store = useStore();
        //text：页面头部面包屑的显示文字，isBack：是否显示页面头部返回按钮
        store.dispatch("setBreadcrumb", {
            text: "系统设置 / 管理员管理",
            isBack: false,
        });
        const formState = ref({
            id: "",
            contactName: "",
            contactMobile: "",
            loginId: "",
            loginPw: "",
            roleId: "",
            status: "",
            otpStatus: "",
        });
        const dataSource = ref([]);
        const columns = reactive([
            {
                title: "用户账号",
                dataIndex: "login_id",
                key: "login_id",
            },
            {
                title: "联系人",
                dataIndex: "contact_name",
                key: "contact_name",
            },
            {
                title: "联系电话",
                dataIndex: "contact_mobile",
                key: "contact_mobile",
            },
            {
                title: "账号角色",
                dataIndex: "role_id",
                key: "role_id",
            },

            {
                title: "创建日期",
                dataIndex: "create_time",
                key: "create_time",
            },
            {
                title: "状态",
                dataIndex: "status",
                key: "status",
                slots: { customRender: "status" },
            },
            {
                title: "操作",
                key: "action",
                slots: { customRender: "action" },
            },
        ]);
        const pagination = reactive({
            current: 1,
            pageSize: 10,
            total: 0,
        });
        return {
            dataSource,
            columns,
            pagination,
            formState,
            isLoading: ref(false),
            visible: ref(false),
            visible2: ref(false),
            activeItem: ref({}),
        };
    },
    data() {
        return {
            roleList: [],
            contactName: "",
            contactMobile: "",
            loginId: "",
            loginPw: "",
            roleId: "",
            status: "",
            rules: {
                contactName: {
                    required: true,
                    message: "不能为空",
                    trigger: "blur",
                },
                contactMobile: [
                    {
                        required: true,
                        message: "不能为空",
                        trigger: "blur",
                    },
                    {
                        trigger: "blur",
                        validator: validator.mobile,
                    },
                ],
                loginId: [
                    {
                        required: true,
                        message: "不能为空",
                        trigger: "blur",
                    },
                ],
                loginPw: [
                    {
                        required: true,
                        message: "不能为空",
                        trigger: "blur",
                    },
                    {
                        trigger: "blur",
                        message: "密码格式错误",
                        pattern: /^[0-9A-Za-z_\\-]{6,32}$/,
                    },
                ],
                roleId: {
                    required: true,
                    message: "不能为空",
                    trigger: "change",
                    type: "number",
                },
                status: {
                    required: true,
                    message: "不能为空",
                    trigger: "change",
                },
                otpStatus: {
                    required: true,
                    message: "不能为空",
                    trigger: "change",
                },
            },
        };
    },
    mounted() {
        httpRequest.post("getManagerRoleOptions", {}).then((res) => {
            this.roleList = res.data.map((e) => {
                return { value: e.id, label: e.name };
            });
        });
        this.getList();
    },
    methods: {
        getList() {
            this.isLoading = true;
            httpRequest
                .post("getManagerUserList", { page: this.pagination.current, pageSize: this.pagination.pageSize })
                .then((res) => {
                    this.dataSource = res.data.data;
                    this.pagination.total = res.data.total;
                })
                .finally(() => {
                    this.isLoading = false;
                });
        },
        handleTableChange(page) {
            this.pagination.current = page.current;
            this.getList();
        },
        deleteAdmin(item) {
            Modal.confirm({
                title: "系统提示",
                content: "确认删除当前管理员？",
                okText: "确认",
                cancelText: "取消",
                onOk: () => {
                    return new Promise((res) => {
                        httpRequest
                            .post("deleteManagerUser", { loginId: item.login_id })
                            .then(() => {
                                message.success("删除管理员成功");
                                this.getList();
                            })
                            .catch(() => {
                                message.warning({ content: "管理员删除失败", key: "error" });
                            })
                            .finally(() => {
                                this.isLoading = false;
                                res();
                            });
                    });
                },
            });
        },
        editAdmin(item) {
            this.rules.loginPw = {
                trigger: "blur",
                message: "密码格式错误",
                pattern: /^[0-9A-Za-z_\\-]{6,32}$/,
            };
            if (this.$refs.form1 && this.$refs.form1.resetFields) {
                this.$refs.form1.resetFields();
            }
            this.formState = { ...baseUtil.LineToHump(item), loginPw: "" };
            console.log(this.formState);
            this.visible = true;
        },
        addAdmin() {
            this.rules.loginPw = [
                {
                    required: true,
                    message: "不能为空",
                    trigger: "blur",
                },
                {
                    trigger: "blur",
                    message: "密码格式错误",
                    pattern: /^[0-9A-Za-z_\\-]{6,32}$/,
                },
            ];
            if (this.$refs.form1 && this.$refs.form1.resetFields) {
                this.$refs.form1.resetFields();
            }
            this.formState = {
                id: "",
                contactName: "",
                contactMobile: "",
                loginId: "",
                loginPw: "",
                roleId: "",
                status: "",
            };
            this.visible = true;
        },
        confirm() {
            this.$refs.form1.validate().then(() => {
                const url = this.formState.id ? "editManagerUser" : "createManagerUser";
                const msg = this.formState.id ? "修改成功" : "创建成功";
                httpRequest.post(url, this.formState).then(() => {
                    this.visible = false;
                    this.getList();
                    message.success(msg);
                });
            });
        },
        closeModal() {
            this.visible = false;
        },
        closeModal2() {
            this.visible = false;
        },
        detail(item) {
            httpRequest.post("getManagerUserDetail", { loginId: item.login_id }).then((res) => {
                this.activeItem = res.data;
                if(!this.activeItem.otp_secret_key){
                    httpRequest.post("更新二次验证密钥", { loginId: item.login_id,authCode:''}).then((res) => {
                        this.activeItem.otp_url = res.data.otp_url;
                        QRCode.toDataURL(this.activeItem.otp_url).then((url) => {
                            this.activeItem.qrcodeDataUrl = url;
                        });
                        this.visible2 = true;
                    });
                }else{
                    QRCode.toDataURL(this.activeItem.otp_url).then((url) => {
                        this.activeItem.qrcodeDataUrl = url;
                    });
                }
                this.visible2 = true;
            });
        },
        updateSecret(item){
            httpRequest.post("更新二次验证密钥", { loginId: item.login_id,authCode:"" }).then((res) => {
                this.activeItem = res.data;
                QRCode.toDataURL(this.activeItem.otp_url).then((url) => {
                    this.activeItem.qrcodeDataUrl = url;
                });
                this.visible2 = true;
            });
        }
    },
};
</script>
<style lang="less" scoped>
.line {
    width: 100%;
    margin: 20px 0;
    border-top: 1px solid #eee;
}
.span-green {
    display: flex;
    align-items: center;
    &:before {
        content: "";
        display: block;
        width: 4px;
        height: 4px;
        border-radius: 2px;
        margin-right: 5px;
        background: #14ce79;
    }
}
.span-red {
    display: flex;
    align-items: center;
    &:before {
        content: "";
        display: block;
        width: 4px;
        height: 4px;
        border-radius: 2px;
        margin-right: 5px;
        background: #fe4e50;
    }
}
</style>
